<?php

namespace App\Http\Resources\Home\StoreResource;

use App\Models\Goods;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\DB;

class StoreCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $goods = new  Goods();
        return [
            'data' => $this->collection->map(function ($item) use ($goods) {
                return [
                    'id' => $item->id,
                    'store_logo' => $item->store_logo,
                    'comment_rate' => $item->comments_count == 0 ? 100 : round((($item->good_comment ?? 0) / $item->comments_count) * 100, 2),
                    'store_name' => $item->store_name,
                    'area_info' => $item->area_info,
                    'store_address' => $item->store_address,
                    'store_company_name' => $item->store_company_name,
                    'goods_list' => $goods
                        ->where('store_id', $item->id)
                        ->where('goods_status', 1)
                        ->select('goods_name', 'goods_subname', 'goods_master_image', 'goods_price', 'goods_stock')
                        ->get(),
                    'distance' => $item->distance > 1000 ? round($item->distance / 1000, 2) . 'km' : round($item->distance, 2) . 'm',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s'),
                ];
            }),
            // 'data'=>$this->collection,
            'total' => $this->total(), // 数据总数
            'per_page' => $this->perPage(), // 每页数量
            'current_page' => $this->currentPage(), // 当前页码
        ];
    }
}
